package com.lzs.bootsafety.common.util.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author  zhanshi Liu
 * @date    2020/04/01
 * @website www.jhmsona.cn
 * @weChat
 */
public class ExcelUtil<T> {
    public void write(HttpServletResponse response,List<T> dataList) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(System.currentTimeMillis()+ ".xlsx", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName );
            response.setHeader("fileName", fileName);
            EasyExcel.write(response.getOutputStream(), dataList.get(0).getClass()).autoCloseStream(Boolean.FALSE).sheet("用户数据").doWrite(dataList);
        } catch (IOException e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

}
